package while_lang.ast.stmts;

import while_lang.ast.Exp;
import while_lang.ast.Stmt;
import while_lang.semantics.State;
import while_lang.semantics.SymbolTable;
import while_lang.semantics.Type;
import while_lang.semantics.Variable;

/** Nodo del AST de While que representa una sentencia de declaración de 
 *  variable.
 * 	@author Leonardo Val
 */
public class Declaration extends Stmt {
	public final Type type;
	public final String id;
	public final Exp expression;
	
	public Declaration(Type type, String id) {
		this(type, id, null);
	}
	
	public Declaration(Type type, String id, Exp expression) {
		this.type = type;
		this.id = id;
		this.expression = expression;
	}

	@Override public String unparse() {
		String result = type.unparse() +" "+ id;
		if (expression != null) {
			result += " "+ expression.unparse();
		}
		return result;
	}

	@Override public State evaluate(State state) {
		Variable var = state.declare(new Variable(id, type));
		if (expression != null) {
			var.assign(expression.evaluate(state));
		}
		return state;
	}

	@Override public SymbolTable checkTypes(SymbolTable table) {
		/* Si hay una expresión de iniciación hay que controlar que su tipo
		 * se compatible con el de la declaración. Luego hay que agregar la
		 * declaración a la tabla.
		 * */
		
		while_lang.semantics.Declaration d = new while_lang.semantics.Declaration(this.id, this.type);
		
		if (this.expression != null){
			if(!this.type.isCompatible(this.expression.checkTypes(table))){
				table.addError("ERROR: la exp no es compatible con el tipo " + type.unparse());
			}
			
			d.hasValue = true;
			
			
		
		}
		table.declare(d);

		return table;
		
	}
	
	@Override public String toString() {
		if (expression == null) {
			return "Declaration("+ type +", \""+ id +"\")";
		} else {
			return "Declaration("+ type +", \""+ id +"\", "+ expression +")";
		}
	}

	@Override public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((expression == null) ? 0 : expression.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((type == null) ? 0 : type.hashCode());
		return result;
	}

	@Override public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Declaration other = (Declaration) obj;
		if (expression == null) {
			if (other.expression != null)
				return false;
		} else if (!expression.equals(other.expression))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (type == null) {
			if (other.type != null)
				return false;
		} else if (!type.equals(other.type))
			return false;
		return true;
	}

}
